package cn.yza.线程.异步;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/** 两任务组合，都要完成
 * @author Honglixi
 * @create 2021-11-06 15:45
 */
public class Test2 {
    public static ExecutorService executor = Executors.newFixedThreadPool(10);
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //任务1有返回值，任务2没有返回值
//        CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
//            System.out.println("当前线程" + Thread.currentThread().getId());
//            int i = 10 / 2;
//            System.out.println("运行结果" + i);
//            return i;
//        }, executor).thenRunAsync(() -> {
//            System.out.println("任务二启动了");
//        }, executor);

        //两个任务都完成后再执行
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务1线程" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("任务1完成");
            return i;
        }, executor);

        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务2线程" + Thread.currentThread().getId());

            System.out.println("任务2完成");
            return "Hello World";
        }, executor);

        future1.runAfterBothAsync(future2,() -> {
            System.out.println("任务3开始");
        },executor);//不能感谢结果

        //void accept(T t, U u); 有返回结果
        future1.thenAcceptBothAsync(future2,(f1,f2) -> {
            System.out.println("任务4开始，结果为" + f1 + f2);
        },executor);

        //既接受返回值，又能自己返回数据
        CompletableFuture<String> res = future1.thenCombineAsync(future2, (f1, f2) -> {
            System.out.println("任务5开始，结果为" + f1 + f2);
            return "嘻嘻嘻";
        }, executor);
        System.out.println(res.get());
    }
}
